{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <style>
        /* dataTables列内容居中 */
        #project_product > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #project_product > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        ul.parsley-errors-list {
            list-style-type: none;
            color: red;
            padding-left: 0;
            margin-bottom: 0;
        }
    </style>
{% endblock %}

{% block content %}

    <div class="row">
        {% if user.is_superuser %}
        <div class="col-sm-7 pull-left" style="margin-bottom: 3px; margin-top: 3px">
            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" id="add-product-modal"
                        data-target="#productModal" onclick="addProduct();">
                <i class="fa fa-plus-square"></i>
                <span class="bigger-110">新增主机</span>
            </button>
        </div>
        {% endif %}
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box">
                <!-- dataTable -->
                <div class="box-body">
                    <table id="project_product" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>产品名称</th>
                            <th>主管部门</th>
                            <th>安全等级</th>
                            <th>产品描述</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for product in project_product %}
                            <tr>
                                <td>{{ product.id }}</td>
                                <td>{{ product.product_name }}</td>
                                <td>{{ product.product_department }}</td>
                                <td>{{ product.product_level }}</td>
                                <td>{{ product.product_memo }}</td>
                                <td>
                                    <button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-id="{{ product.id }}"
                                            data-target="#productModal">修改</button>
                                    <button type="button" class="btn btn-danger btn-xs delete" data-id="{{ product.id }}">删除</button>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
    </div>
    <!-- /.row -->

    <div class="modal fade" id="productModal" tabindex="-1" role="dialog"
             aria-labelledby="productModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="productModalLabel">
                            新增主机
                        </h4>
                    </div>
                    <div class="modal-body">
                        <form id="add_product" class="main form-horizontal">
                            <fieldset>
                                <div class="form-group">
                                    <label for="product_name" class="col-sm-2 control-label"><span class="text-red">*</span>产品名称</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="product_name" name="product_name" required maxlength="64">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="product_memo" class="col-sm-2 control-label">产品描述</label>
                                    <div class="col-sm-9">
                                        <textarea type="text" class="form-control" id="product_memo" name="product_memo"></textarea>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="product_department" class="col-sm-2 control-label">主管部门</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="product_department" name="product_department" maxlength="16">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="product_level" class="col-sm-2 control-label">安全等级</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="product_level" name="product_level" maxlength="8">
                                    </div>
                                </div>
                            </fieldset>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="btnSave">确认
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>

{% endblock %}


{% block js %}
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'parsley/dist/parsley.min.js' %}"></script>
    <script src="{% static 'parsley/dist/zh_cn.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script>
        $(function () {
            project_product_table = $('#project_product').DataTable({
                language: {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "快速搜索:",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               },
                columnDefs: [{
                    'targets': [-1,],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            $("[data-toggle='tooltip']").tooltip();

            $.fn.serializeJson = function () {
                let serializeObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (serializeObj[this.name]) {
                        if ($.isArray(serializeObj[this.name])) {
                            serializeObj[this.name].push(this.value);
                        } else {
                            serializeObj[this.name] = [serializeObj[this.name], this.value];
                        }
                    } else {
                        serializeObj[this.name] = this.value;
                    }
                });
                return serializeObj;
            };
        });

        function add_or_change_product(protocol, url){
            let obj = $("#add_product")
            let data = obj.serializeJson();
            let status = obj.parsley().validate();
            if (status) {
                $.ajax({
                    type: protocol,
                    url: url,
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    success: function () {
                        $('#productModal').modal('hide')
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: "保存成功！",
                            buttons: {
                                   ok: function () {
                                       window.location.reload()
                                },
                            },
                        })
                    },
                    error: function (response) {
                        if(response.responseJSON.hasOwnProperty('product_name')){
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: response.responseJSON.product_name,
                            })
                        } else {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: '请修改错误！'+response.responseText,
                            })
                        }
                    }
                });
            }
        }
        
        function addProduct(){
            document.getElementById('add_product').reset();
            $('#add_product').parsley().destroy();
            $('.modal-title').text('新增');
            $("#btnSave").unbind('click').click(function () {
                add_or_change_product('POST',"/api/projectproduct/");
            });
        }

        $('#project_product tbody').on('click', '.delete', function () {
            let pk = $(this).attr('data-id');
            let tr_obj = $(this).parents('tr');
            $.confirm({
                title: 'Tips',
                content: '确定要删除这条记录么？',
                type: 'red',
                buttons: {
                    Ok: function () {
                        $.ajax({
                            url: '/api/projectproduct/' + pk + '/',
                            method: 'DELETE',
                            success: function () {
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: '删除成功！',
                                    buttons: {
                                           ok: function () {
                                               window.location.reload()
                                        },
                                    },
                                })
                            },
                            error: function (data) {
                                //console.log(data.responseText)
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: '删除失败！',
                                })
                            }
                        })
                    },
                    Cancel: function () {
                        //
                    }
                }
            });
        });
        
        // 更新
        $('#project_product tbody').on('click', '.modify', function () {
            let project_product_id = $(this).attr('data-id');
            let project_product_ops = $("#btnSave")
            $('.modal-title').text('修改');
            $('#add_product').parsley().destroy();
            document.getElementById('add_product').reset()
            $.get('/api/projectproduct/' + project_product_id + '/', function (data) {
                $('#product_name').val(data.product_name);
                $('#product_memo').val(data.product_memo);
                $('#product_level').val(data.product_level);
                $('#product_department').val(data.product_department);
            });

            project_product_ops.unbind('click').on('click', function () {
                add_or_change_product('PUT','/api/projectproduct/' + project_product_id + '/');
            });
        });
    
    </script>

{% endblock %}